package com.lai.gulimall.ware.service.impl;

import com.lai.common.constant.WareConstant;
import com.lai.common.utils.R;
import com.lai.gulimall.ware.entity.PurchaseDetailEntity;
import com.lai.gulimall.ware.entity.WareSkuEntity;
import com.lai.gulimall.ware.fegin.ProductFeignService;
import com.lai.gulimall.ware.service.PurchaseDetailService;
import com.lai.gulimall.ware.service.WareSkuService;
import com.lai.gulimall.ware.vo.MergeVo;
import com.lai.gulimall.ware.vo.PurchaseDoneVo;
import com.lai.gulimall.ware.vo.PurchaseItemDoneVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lai.common.utils.PageUtils;
import com.lai.common.utils.Query;

import com.lai.gulimall.ware.dao.PurchaseDao;
import com.lai.gulimall.ware.entity.PurchaseEntity;
import com.lai.gulimall.ware.service.PurchaseService;
import org.springframework.transaction.annotation.Transactional;


@Service("purchaseService")
public class PurchaseServiceImpl extends ServiceImpl<PurchaseDao, PurchaseEntity> implements PurchaseService {

    @Autowired
    PurchaseDetailService purchaseDetailService;

    @Autowired
    WareSkuService wareSkuService;

    @Autowired
    ProductFeignService productFeignService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                new QueryWrapper<PurchaseEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public PageUtils queryPageUnreceive(Map<String, Object> params) {
        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                new QueryWrapper<PurchaseEntity>().eq("status", 0).or().eq("status", 1)
        );

        return new PageUtils(page);
    }

    @Transactional
    @Override
    public void mergePurchase(MergeVo mergeVo) {
        Long purchaseId = mergeVo.getPurchaseId();
        if (purchaseId == null) {//如果没有提交采购单id 则新建一个
            PurchaseEntity purchaseEntity = new PurchaseEntity();
            purchaseEntity.setStatus(WareConstant.PurchaseStatusEnum.CREATED.getCode());
            purchaseEntity.setCreateTime(new Date());
            purchaseEntity.setUpdateTime(new Date());
            this.save(purchaseEntity);
            //保存之后就会有id值  ，把id保存到purchaseId里面
            purchaseId = purchaseEntity.getId();
        } else {
            List<Long> items = mergeVo.getItems();
            Long finalPurchaseId = purchaseId;
            List<PurchaseDetailEntity> collect = items.stream().map(i -> {
                PurchaseDetailEntity detailEntity = new PurchaseDetailEntity();
                detailEntity.setId(i);//设置id  需要修改实体类里的idType
                detailEntity.setPurchaseId(finalPurchaseId);//设置采购单id
                detailEntity.setStatus(WareConstant.PurchaseDetailStatusEnum.ASSIGNED.getCode());
                return detailEntity;
            }).collect(Collectors.toList());
            purchaseDetailService.updateBatchById(collect);

            PurchaseEntity purchaseEntity = new PurchaseEntity();
            purchaseEntity.setId(purchaseId);
            purchaseEntity.setUpdateTime(new Date());
            this.updateById(purchaseEntity);
        }

    }

    @Override
    public void received(List<Long> ids) {
        //1、确认当前采购单是新建或者已分配状态
        List<PurchaseEntity> collect = ids.stream().map(id -> {
            //根据传入的采购单id获取采购详情
            PurchaseEntity byId = this.getById(id);
            return byId;
        }).filter(item -> {
            //需要过滤掉 采购状态为 已领取 已完成 有异常  的采购单
            if (item.getStatus() == WareConstant.PurchaseStatusEnum.CREATED.getCode() ||
                    item.getStatus() == WareConstant.PurchaseStatusEnum.ASSIGNED.getCode()) {
                return true;
            }
            return false;
        }).map(item -> { //过滤完 设置最新状态  已领取
            item.setStatus(WareConstant.PurchaseStatusEnum.RECEIVE.getCode());
            item.setUpdateTime(new Date());
            return item;
        }).collect(Collectors.toList());

        //2、批量修改采购单的状态
        this.updateBatchById(collect);

        //3、根据采购单id改变采购项 细节 的状态
        collect.forEach((item) -> {
            List<PurchaseDetailEntity> entities = purchaseDetailService.listDetailByPurchaseId(item.getId());
            List<PurchaseDetailEntity> detailEntities = entities.stream().map(entity -> {
                PurchaseDetailEntity purchaseDetailEntity = new PurchaseDetailEntity();
                purchaseDetailEntity.setId(entity.getId());
                purchaseDetailEntity.setStatus(WareConstant.PurchaseDetailStatusEnum.BUYING.getCode());
                return purchaseDetailEntity;
            }).collect(Collectors.toList());
            purchaseDetailService.updateBatchById(detailEntities);
        });


    }

    @Transactional
    @Override
    public void done(PurchaseDoneVo purchaseDoneVo) {
       //1、改变采购项状态
        AtomicReference<Boolean> flag = new AtomicReference<>(true);
        List<PurchaseItemDoneVo> items = purchaseDoneVo.getItems();
        List<PurchaseDetailEntity> updates = new ArrayList<>();
        items.forEach((item) ->{
            PurchaseDetailEntity purchaseDetailEntity = new PurchaseDetailEntity();
            //如果采购项的状态为采购失败
            if(item.getStatus() == WareConstant.PurchaseDetailStatusEnum.HASERROR.getCode()){
                //改变flag的值
                flag.set(false);
                purchaseDetailEntity.setStatus(item.getStatus());
            }else{
                purchaseDetailEntity.setStatus(WareConstant.PurchaseDetailStatusEnum.FINISH.getCode());
                //将成功采购的物品进行入库
                PurchaseDetailEntity entity = purchaseDetailService.getById(item.getItemId());//根据采购项的id 查出详细信息
                WareSkuEntity wareSkuEntity = new WareSkuEntity();
                
                //根据商品id查出商品名称(远程调用 product)
                //TODO 异常出现以后不回滚
                try{
                    R r = productFeignService.queryInfoById(entity.getSkuId());
                    if(r.getCode() == 0){
                        Map<String,Object> data =  (Map<String,Object>) r.get("data");
                        wareSkuEntity.setSkuName((String) data.get("skuName"));
                    }
                }catch (Exception e){

                }

                wareSkuEntity.setSkuId(entity.getSkuId());
                wareSkuEntity.setWareId(entity.getWareId());
                wareSkuEntity.setStock(entity.getSkuNum());
                wareSkuEntity.setStockLocked(0);
                //商品入库
                wareSkuService.addStock(wareSkuEntity);

            }
            purchaseDetailEntity.setId(item.getItemId());
            updates.add(purchaseDetailEntity);
        });
        purchaseDetailService.updateBatchById(updates);


        //2、改变采购单状态（如果所有采购项的状态是已完成，采购项的状态就可以改为已完成   有一个采购项的状态是未完成，则为有异常）
        PurchaseEntity purchaseEntity = new PurchaseEntity();
        purchaseEntity.setId(purchaseDoneVo.getId());
        //根据flag的值判断采购单的状态
        purchaseEntity.setStatus(flag.get()?WareConstant.PurchaseStatusEnum.FINISH.getCode():WareConstant.PurchaseStatusEnum.HASERROR.getCode());
        purchaseEntity.setUpdateTime(new Date());
        this.updateById(purchaseEntity);



    }

}